/**
 * 初始化右键菜单功能
 * @param editor 编辑器实例
 */
import { Dialog } from '../../components/dialog/Dialog'
import { EditorZone, ElementType } from '../../editor'
import { Command } from '../../editor/core/command/Command'
import { IContextMenuContext } from '../../editor/interface/contextmenu/ContextMenu'
import { Signature } from '../../components/signature/Signature'

export default function initContextMenu(editor: any, commentList: any[]): void {
  // 检查editor和register对象是否存在
  if (editor && editor.register) {
    // 使用正确的注册方法注册右键菜单
    editor.register.contextMenuList([
      // 批注菜单
      {
        name: '批注',
        when: (payload: IContextMenuContext) => {
          return !payload.isReadonly && payload.editorHasSelection && payload.zone === EditorZone.MAIN
        },
        callback: (command: Command) => {
          new Dialog({
            title: '批注',
            data: [
              {
                type: 'textarea',
                label: '批注',
                height: 100,
                name: 'value',
                required: true,
                placeholder: '请输入批注'
              }
            ],
            onConfirm: payload => {
              const value = payload.find(p => p.name === 'value')?.value
              if (!value) return
              const groupId = command.executeSetGroup()
              if (!groupId) return
              // 假设 commentList 是全局变量，先初始化或使用全局对象存储
              commentList.push({
                id: groupId,
                content: value,
                userName: 'Hufe',
                rangeText: command.getRangeText(),
                createdDate: new Date().toLocaleString()
              })
            }
          })
        }
      },
      // 签名菜单
      {
        key: 'signature',
        name: '添加签名',
        when: (payload: IContextMenuContext) => {
          return !payload.isReadonly && payload.editorTextFocus
        },
        callback: (command: Command) => {
          // 简单的签名实现
          // command.executeInsertText('张三')
          new Signature({
            onConfirm(payload) {
              if (!payload) return
              const { value, width, height } = payload
              if (!value || !width || !height) return
              command.executeInsertElementList([
                {
                  value,
                  width,
                  height,
                  type: ElementType.IMAGE
                }
              ])
            }
          })
        }
      },
      // 格式整理菜单
      {
        key: 'format',
        name: '格式整理',
        when: (payload: IContextMenuContext) => {
          return !payload.isReadonly
        },
        callback: (command: Command) => {
          command.executeWordTool()
        }
      }
    ])
  }
}
